package com.sky.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/images")
public class StaticResourceController {

    @Value("${visa.path.country-images}")
    private String countryImagesPath;

    @Value("${visa.path.user-material-images}")
    private String userMaterialImagesPath;

    @GetMapping("/country/{filename:.+}")
    public void getCountryImage(@PathVariable String filename, HttpServletResponse response) {
        serveImage(Paths.get(countryImagesPath, filename), response);
    }

    @GetMapping("/usermaterial/{filename:.+}")
    public void getUserMaterialImage(@PathVariable String filename, HttpServletResponse response) {
        // 处理可能的完整URL情况
        if (filename.contains("/")) {
            filename = filename.substring(filename.lastIndexOf("/") + 1);
        }
        
        // 处理可能的wxfile情况
        if (filename.startsWith("wxfile")) {
            log.warn("接收到微信临时文件路径: {}", filename);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        serveImage(Paths.get(userMaterialImagesPath, filename), response);
    }

    private void serveImage(Path imagePath, HttpServletResponse response) {
        try {
            if (!Files.exists(imagePath)) {
                log.warn("图片不存在: {}", imagePath);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 添加缓存控制头
            response.setHeader("Cache-Control", "max-age=31536000");
            response.setHeader("Pragma", "public");
            
            String contentType = Files.probeContentType(imagePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            response.setContentType(contentType);

            Files.copy(imagePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("读取图片失败: {}", imagePath, e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}